<template>
  <div class="history-container">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>历史记录</span>
          <div class="filter-container">
            <el-select v-model="statusFilter" placeholder="状态过滤" clearable style="width: 120px">
              <el-option label="全部" value=""></el-option>
              <el-option label="处理中" value="processing"></el-option>
              <el-option label="成功" value="success"></el-option>
              <el-option label="失败" value="failed"></el-option>
              <el-option label="等待中" value="pending"></el-option>
            </el-select>
            <el-select v-model="modelFilter" placeholder="模型过滤" clearable style="width: 150px">
              <el-option label="全部" value=""></el-option>
              <el-option 
                v-for="model in models" 
                :key="model.modelName" 
                :label="model.displayName" 
                :value="model.modelName"
              ></el-option>
            </el-select>
            <el-button :icon="Search" @click="loadRecords"></el-button>
            <el-button :icon="Refresh" @click="loadRecords(true)"></el-button>
          </div>
        </div>
      </template>

      <el-table :data="records" style="width: 100%" v-loading="loadingRecords">
        <el-table-column type="expand">
          <template #default="props">
            <div class="record-details">
              <div class="detail-item">
                <b>提示词:</b> {{ props.row.prompt }}
              </div>
              <div class="detail-item" v-if="props.row.negativePrompt">
                <b>负面提示词:</b> {{ props.row.negativePrompt }}
              </div>
              <div class="detail-item">
                <b>参数:</b> 
                <div class="params-grid">
                  <span>步数: {{ props.row.steps || '-' }}</span>
                  <span>CFG: {{ props.row.cfgScale || '-' }}</span>
                  <span>种子值: {{ props.row.seed !== undefined && props.row.seed !== null ? props.row.seed : '-' }}</span>
                  <span v-if="props.row.samplerName">采样器: {{ props.row.samplerName }}</span>
                  <span v-if="props.row.scheduler">调度器: {{ props.row.scheduler }}</span>
                  <span v-if="props.row.denoisingStrength">降噪强度: {{ props.row.denoisingStrength }}</span>
                  <span v-if="props.row.batchSize">批次大小: {{ props.row.batchSize }}</span>
                  <span v-if="props.row.restoreFaces !== undefined">恢复面部: {{ props.row.restoreFaces ? '是' : '否' }}</span>
                  <span v-if="props.row.tiling !== undefined">平铺模式: {{ props.row.tiling ? '是' : '否' }}</span>
                  <span v-if="props.row.enableHr !== undefined">高清修复: {{ props.row.enableHr ? '是' : '否' }}</span>
                  <span v-if="props.row.hrScale">HR缩放: {{ props.row.hrScale }}</span>
                  <span v-if="props.row.hrUpscaler">HR放大器: {{ props.row.hrUpscaler }}</span>
                  <span v-if="props.row.hrSecondPassSteps">HR二次步数: {{ props.row.hrSecondPassSteps }}</span>
                  <span v-if="props.row.modelHash">模型哈希: {{ props.row.modelHash }}</span>
                </div>
              </div>
              <div class="detail-item" v-if="props.row.errorMessage">
                <b>错误信息:</b> {{ props.row.errorMessage }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="预览" width="80" fixed>
          <template #default="scope">
            <el-image 
              v-if="getImageUrl(scope.row)" 
              :src="getImageUrl(scope.row)" 
              fit="cover"
              :preview-src-list="[getImageUrl(scope.row)]"
              style="width: 60px; height: 60px; border-radius: 4px;"
            ></el-image>
            <div 
              v-else 
              class="empty-image"
              style="width: 60px; height: 60px; border-radius: 4px; display: flex; align-items: center; justify-content: center; background-color: #f5f7fa; color: #909399; font-size: 12px;"
            >
              无图像
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="taskId" label="任务ID" width="120" show-overflow-tooltip></el-table-column>
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="statusTypeMap[scope.row.status]">{{ statusTextMap[scope.row.status] }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="modelName" label="模型" width="120" show-overflow-tooltip></el-table-column>
        
        <el-table-column label="尺寸" width="80">
          <template #default="scope">
            {{ scope.row.width }}×{{ scope.row.height }}
          </template>
        </el-table-column>
        
        <el-table-column label="提示词" min-width="250" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.prompt }}
          </template>
        </el-table-column>
        
        <el-table-column label="参数" width="200">
          <template #default="scope">
            <div class="param-brief">
              <div v-if="scope.row.samplerName">采样器: {{ scope.row.samplerName }}</div>
              <div>步数: {{ scope.row.steps || '-' }}</div>
              <div>CFG: {{ scope.row.cfgScale || '-' }}</div>
              <div v-if="scope.row.seed !== undefined && scope.row.seed !== null">种子: {{ scope.row.seed }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="生成时间" width="100">
          <template #default="scope">
            <span v-if="scope.row.generationTime">{{ (scope.row.generationTime / 1000).toFixed(2) }}秒</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button 
              type="success" 
              size="small" 
              @click="downloadImageById(scope.row)"
              :disabled="!getImageUrl(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Search } from '@element-plus/icons-vue'
import { 
  getRecords, 
  type Txt2ImgResponse,
  type ModelConfig
} from '@/api/text2img'

// 属性定义
const props = defineProps<{
  models: ModelConfig[]
  generating: boolean
}>()

// 状态管理
const loadingRecords = ref(false)
const records = ref<Txt2ImgResponse[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')
const modelFilter = ref('')

// 状态映射
const statusTypeMap: Record<string, string> = {
  'pending': 'info',
  'processing': 'warning',
  'success': 'success',
  'failed': 'danger'
}

const statusTextMap: Record<string, string> = {
  'pending': '等待中',
  'processing': '处理中',
  'success': '成功',
  'failed': '失败'
}

// 从imageUrls字符串中提取第一个URL
function getImageUrlFromUrls(imageUrls?: string | string[]): string | null {
  if (!imageUrls) return null
  
  // 如果imageUrls已经是数组，直接取第一个元素
  if (Array.isArray(imageUrls)) {
    return imageUrls.length > 0 ? imageUrls[0] : null
  }
  
  // 如果是字符串，尝试解析为JSON
  try {
    const urls = JSON.parse(imageUrls) as string[]
    return urls && urls.length > 0 ? urls[0] : null
  } catch (error) {
    console.error('解析图像URL错误:', error)
    return imageUrls || null // 如果无法解析，则返回原始字符串
  }
}

// 获取图像URL（支持两种格式）
function getImageUrl(record: Txt2ImgResponse): string | null {
  if (record.imageUrl) {
    return record.imageUrl
  }
  
  return getImageUrlFromUrls(record.imageUrls)
}

// 下载历史记录中的图像
function downloadImageById(record: Txt2ImgResponse) {
  const imageUrl = getImageUrl(record)
  if (!imageUrl) return
  
  const link = document.createElement('a')
  link.href = imageUrl
  link.download = `image_${record.taskId}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 加载历史记录
async function loadRecords(reset: boolean = false) {
  if (reset) {
    currentPage.value = 1
  }
  
  loadingRecords.value = true
  try {
    const response = await getRecords(
      currentPage.value, 
      pageSize.value,
      statusFilter.value,
      modelFilter.value
    )
    
    if (response.code === 200 && response.data) {
      // 处理可能的不同响应格式
      if (response.data.records) {
        records.value = response.data.records
      } else if (response.data.list) {
        records.value = response.data.list
      } else {
        records.value = []
      }
      
      total.value = response.data.total
      
      // 处理imageUrl字段
      records.value.forEach(record => {
        if (!record.imageUrl && record.imageUrls) {
          const url = getImageUrlFromUrls(record.imageUrls)
          if (url) {
            record.imageUrl = url
          }
        }
      })
    } else {
      ElMessage.error(response.msg || '加载历史记录失败')
    }
  } catch (error) {
    console.error('加载历史记录错误:', error)
    ElMessage.error('加载历史记录失败')
  } finally {
    loadingRecords.value = false
  }
}

// 分页处理
function handleSizeChange(size: number) {
  pageSize.value = size
  loadRecords()
}

function handleCurrentChange(page: number) {
  currentPage.value = page
  loadRecords()
}

// 格式化日期时间
function formatDateTime(timestamp: string | null) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`
}

function padZero(num: number) {
  return num.toString().padStart(2, '0')
}

// 生命周期钩子
onMounted(() => {
  loadRecords()
})
</script>

<style scoped>
.history-container {
  margin-top: 20px;
  width: 100%;
}

.history-card {
  width: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.record-details {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.detail-item {
  margin-bottom: 8px;
  line-height: 1.5;
}

.params-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 5px;
  margin-top: 5px;
}

.param-brief {
  font-size: 12px;
  line-height: 1.5;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-image {
  text-align: center;
  border: 1px dashed #dcdfe6;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
}
</style> 